package com.gitee.linzl.zuul.gateway.fiters.pre;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.gitee.linzl.zuul.gateway.fiters.AbstractDefaultPreFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import lombok.extern.slf4j.Slf4j;

/**
 * 访问控制：黑名单、白名单
 * 
 * @description
 * @author linzl
 * @email 2225010489@qq.com
 * @date 2018年10月4日
 */
@Component
@Slf4j
public class AccessControlFilter extends AbstractDefaultPreFilter {
	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		// 在黑名单范围内的，禁止访问
		StringBuffer url = request.getRequestURL();
		int httpIndex = url.indexOf("//");
		if (log.isDebugEnabled()) {
			log.debug("路径:{}", url);
			log.debug("httpIndex:{}", httpIndex);
		}

		String uri = request.getRequestURI();
		String tempContextUrl = url.delete(url.length() - uri.length(), url.length()).substring(httpIndex + 2);
		if (log.isDebugEnabled()) {
			log.debug("uri:{}", uri);
			log.debug("ip,端口或域名:{}", tempContextUrl);
		}

		try {
			// 域名限制访问

			// IP限制访问
		} catch (Exception e) {
			JSONObject error = new JSONObject();
			error.put("errCode", "1000");
			error.put("errMsg", "无权访问");
			setFailedResponse(error.toString(), 200);
		}
		return null;
	}

}
